
// OOP

    organizational_action = {
	save_form_workspace : function(elements){
	    $("body").on("click",elements,function(){
		/*ORGCHART SAVE*/
		var form_type = $(this).attr("data-form-type");
		
		switch(form_type){
		    case "organizational_chart":
		    var errorMessage = "";
			var json_encode = $("body").data();
			var workspace_width = $(".form_size_width").val();
            var workspace_height = $(".form_size_height").val();
            var json_node = json_encode['nodes'];
            var json_line = json_encode['lines'];
			json_encode['title'] = $("#workspace_title").val();
			json_encode['description'] = $("#workspace_description").val();
			json_encode['status'] = $("#workspace_status").val();
			json_encode['width'] = $(".form_size_width").val();
			json_encode['height'] = $(".form_size_height").val();

			//VALIDATION STARTS HERE

			if($("#workspace_title").val()=="" || $("#workspace_status").val()=="null"){
                errorMessage = "Please fill out the required fields";
            }
            if(json_haselement(json_node)== false || json_haselement(json_line)== false){
				errorMessage = "Your workspace is empty";
			}
            if(errorMessage!=""){
            	showNotification({
                    message: errorMessage,
                    type: "error",
                    autoClose: true,
                    duration: 3
                });
                return;
            }
            //VALIDATION ENDS HERE
			ui.block();
            console.log(json_encode)
			json_encode = JSON.stringify(json_encode);
			$.post("/ajax/orgchart",{action:"saveOrgchart",json_encode:json_encode},function(data){
				// console.log(data)
			    showNotification({
				    message: data,
				    type: "success",
				    autoClose: true,
				    duration: 3
			    });
			     $("#popup_overlay,#popup_container").remove();
			    ui.unblock();
			})	

		    break;
		}
	    });
	}
    }


$(document).ready(function(){
    var pathname = window.location.pathname;
    if(pathname!="/organizational-chart"){
        return;
    }
    ui.block();
    
    //container
    var node_container = '.workspace';
    
    
    /* ORGCHART */
    //get and set nodes from database
    var orgchart_lines = $("#orgchart_lines").text();
    if (orgchart_lines) {
		orgchart_lines = JSON.parse(orgchart_lines);
		var json_body = $("body").data();
		var json_linedata = {};
		
		for (var a=0; a<orgchart_lines.length;a++) {
		    var lines = JSON.parse(orgchart_lines[a]);
		    if(lines['line-type']!="arrow"){
			//append line
			$(node_container).append('<span class="lines '+ lines['line-type'] +
	                                    '" line-class="'+ lines['line-class'] +
	                                    '" parent="'+ lines['parent'] +'" child="'+ lines['child'] +
	                                    '" style="top:'+ lines['top'] +'px;left:'+
	                                    lines['left'] +'px;width:'+ lines['width'] +'px;height:'+
	                                    lines['height'] +'px;background-color:'+
	                                    lines['background-color'] +';"></span>');
		    }else{
			//appendline
			$(node_container).append('<span class="lines arrow" line-class="'+ lines['line-class'] +
	                                         '" parent="'+ lines['parent'] +
	                                         '" child="'+ lines['child'] +
	                                         '" style="top:'+ lines['top'] +'px;left:'+ lines['left'] +'px;'+ lines['border'] +'"></span>');
		    }
		    json_linedata[''+ lines['line-class'] +'_'+lines['line-type']] = {};
	            json_linedata[''+ lines['line-class'] +'_'+lines['line-type']] =  lines;
		}
		json_body['lines'] = json_linedata;
		$("body").data(json_body);
	
    }
    
    
    //get and set nodes from database
    var orgchart_nodes = $("#orgchart_nodes").text();
    var orgchartJson = "";
    var nodeId = "";var userID = "";
    if (orgchart_nodes) {
		orgchart_nodes = JSON.parse(orgchart_nodes);
		for (var a=0; a<orgchart_nodes.length;a++) {
            orgchartJson = JSON.parse(orgchart_nodes[a]);
            nodeId = orgchartJson['node_data_id'];
            userID = orgchartJson['orgchart_user_head'][0];
            //getHeadName(userID,orgchartJson,a,function(data,orgchartJson,ctr){
                if(orgchartJson['node_type']=="box"){
                    orgchartJson['node_type'] = "department";
                }
                // orgchartJson['head_name'] = data;
                nodeDesign(orgchartJson);
                
                if($(".userLevel").val()!=2){
                    $(".node-dragtopoint-wrapper, .node-drag-item-wrapper, .node-remove").addClass("display2")
                    $(".outer-node").addClass("borderTransparent");
                }
            //})
		}
        
    }
    //variables in nodes function
    for (var a=0; a<orgchart_nodes.length;a++) {
        orgchartJson = JSON.parse(orgchart_nodes[a]);
        nodeId = orgchartJson['node_data_id'];
        $("#" + nodeId).find(".node-avatar-wrapper").find("img").attr({
            "width" : "35",
            "height" : ""
        })
        moveLines(nodeId,"");
    }
   
    var node_linecolor = '#424242';
    //initialize node functions on load
    node.mouseoverNode();
    node.mouseleaveNode();
    node.mousedown();
    node.activateNode();
    node.dragAlso();
    node.dropToNode('.node-drag',node_container,node_linecolor);
    node.dragNode(".outer-node",node_container,true,node_linecolor);
    node.resizeNode(node_container,node_linecolor);
    node.resizeStartNode(node_container,node_linecolor);
    //Node Settings
    nodeSettings.minimizeNode(node_linecolor);
    nodeSettings.maximizeNode(node_linecolor);
    //Line Trigger Drag
    /*
     * Add node to the workspace Organizational Chart
     * ('Process Node')
     * 
     */
       
     ui.unblock();
    
     var node_linecolor = '#424242';
    
      $(".orgchart_node").node({
        event       : 'click',
        container   : '.workspace',
        startCount  : 1,
        type        : "department",
        defaultText : "Department Name",
        nodeColor   : "#424242",
        lineColor   : node_linecolor,
        enableRuler : true,
        state       : true,
        settings_property : "organizational_chart"
        });
    
    
   

    // Control Save Workspace
	// Main Function of save is on the formbuilder.js
    /*-----------------------------------------------------*/
    
    // OOP JS Functions Call
	/* Main Workspace */
	    workspace_functions.view_save(".save_workspace");
	
	/* Main Organizational Chart */
	    organizational_action.save_form_workspace(".save_form_workspace");
	// Resize Actual Form
	    $(".orgchart_ws").resize();



	//
    $("body").on("click",".orgchart_user_wrap",function(){
        var node_data_id =  $(".settings-to-json").attr("node-data-id");
        var json_nodes = $("body").data();
        var json_nodes_var = json_nodes['nodes'];
        if($(this).find("input").hasClass("head_user")){
        	json_nodes_var[''+ node_data_id +'']['orgchart_user_head'] = array_store(".head_user","checkbox");
        }else if($(this).find("input").hasClass("asst_head_user")){
        	json_nodes_var[''+ node_data_id +'']['orgchart_dept_assistant'] = array_store(".asst_head_user","checkbox");
        }else if($(this).find("input").hasClass("member_user")){
        	json_nodes_var[''+ node_data_id +'']['orgchart_dept_members'] = array_store(".member_user","checkbox");
        }

    })
     $("body").on("keyup",".orgchart-user-search",function(){
     	var value = $(this).val();
     	var node_data_id = $(".node_data_id").val();
     	var type = $(this).attr("id");
     	getUser(node_data_id,value,type,function(){
    		$('#content-dialog-scroll').perfectScrollbar("update");
    		limitText(".limit-text-wf",19); // set limit of text in the name   
    		$(".tip").tooltip();
    	});
     })
     // $(".workspace.orgchart_ws").resizable({
     //    stop: function(){
     //        alert(1)
     //    }
     // });
    resizeForm($(".orgchart_ws"), "600","orgchart")
    if ($(".workspace.orgchart_ws").find(".outer-node").length >= 1) {
        if (checkFormMinWidth("orgchart") != null) {
			$(".workspace.orgchart_ws").resizable("option", "minWidth", checkFormMinWidth("orgchart"));
        }
        if (checkFormMinHeight("orgchart") != null) {
			$(".workspace.orgchart_ws").resizable("option", "minHeight", checkFormMinHeight("orgchart"));
        }
        $(".workspace.orgchart_ws").css({
            "height": $("#orgchart_height").text()+"px",
            "width": $("#orgchart_width").text()+"px",

        });
        $(".leftPointerRuler-container").css({
        	"height": $("#orgchart_height").text()+"px",
        })
    }
    var pathname = window.location.pathname;
    if($(".userLevel").val()!=2 && pathname=="/organizational_chart"){
    	$('.orgchart_ws').resizable('destroy');
    	$(".orgchart_ws").css({
    		"background":"none"
    	})
    	$(".topPointerRuler-container, .leftPointerRuler-container").addClass("display2")
    	$(".node-process-drag").css({
    		"border-top":"none"
    	})

    }
    var pathname = window.location.pathname;
    if(pathname!="/organizational_chart"){
        return;
    }
	var ws_width = $(".orgchart_ws").outerWidth();
    var ws_height = $(".orgchart_ws").outerHeight();
    $(".form_size_width").val(ws_width)
    $(".form_size_height").val(ws_height)
});

function getHeadName(userID,json,ctr,callback){
    $.ajax({
        type    : "POST",
        url     : "/ajax/orgchart",
        data    : {action:"getHeadName",userID:userID},
        async   : true,
        success : function(data){
            
            callback(data,json,ctr)
        }
    })
}